<?php
require_once('Extension/Controller/Plugin/Abstract.php');

class Extension_Controller_Plugin_Common_View extends Extension_Controller_Plugin_Abstract
{
    //public function routeStartup(Zend_Controller_Request_Abstract $request) {}
    
    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {
        
        self::initView($request);
    }

    //public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {}
    //public function preDispatch(Zend_Controller_Request_Abstract $request) {}
    //public function postDispatch(Zend_Controller_Request_Abstract $request) {}
    //public function dispatchLoopShutdown() {}


    public static function initView(Zend_Controller_Request_Abstract $request)
    {
        $moduleName = $request->getModuleName();

        require_once('Zend/Registry.php');
        if (!Zend_Registry::isregistered('view')) {

            $config = Kbs::initConfig('View');

            if (null != $config->$moduleName) {

                if (null == $config->host) {
                    require_once('Extension/View/Exception.php');
                    throw new Extension_View_Exception('host missing !');
                }

                if (null == $config->encoding) {
                    require_once('Extension/View/Exception.php');
                    throw new Extension_View_Exception('encode setting missing !');
                }

                $viewRenderer = Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer');
                $viewRenderer->initView(PROJECT_ROOT . $config->$moduleName->viewBasePath);
                $host = $config->host;
                $view = $viewRenderer->view;

                $view->addHelperPath($config->helper->path, $config->helper->prefix)
                     ->setEncoding($config->encoding)
                     ->assign(array('host'          =>  $host,
                                    'charset'       =>  $config->encoding,
                                    'pathImages'    =>  $host . $config->$moduleName->pathImages,
                                    'pathJs'        =>  $host . $config->$moduleName->pathJs,
                                    'pathCss'       =>  $host . $config->$moduleName->pathCss));

                Zend_Registry::set('view', $view);
                return $view;

            } else {
                require_once('Extension/View/Exception.php');
                throw new Extension_View_Exception("view setting for module $moduleName hasn't been made up yet. " 
                                                 . "Please check your 'view.ini' file within your configurations.");
            }

        } else {
            return Zend_Registry::get('view');
        }
                
    }


}